<template>
	<view class="my-content">
		<view class="form-box">
			<text class="form-title">*电站头像</text>
			<view class="ava-img" @click="uploadImage('pic')">
				<image :src="formData.pic" mode="widthFix" v-if="formData.pic"></image>
				<text v-else>+</text>
			</view>
		</view>
		<view class="form-box">
			<text class="form-title">*电站名称</text>
			<view class="form-item">
				<input type="text" placeholder="请输入电站名称" v-model="formData.name" />
			</view>
			
			<text class="form-title">*电站属性</text>
			<view class="form-item">
				<input type="text" disabled="true" style="background-color: #ccc;" placeholder="请输入电站属性" v-model="typearr[typeindex]" />
				
				<!-- <picker class="form-item" :range="typearr" @change="onChangeType">
					<view class="picker">
						<text >{{typearr[typeindex]}}</text>
					</view>
				</picker> -->
			</view>
			
			<text class="form-title mt20">*省市区</text>
			<picker class="form-item" mode="region" :value="region" @change="onChangeRegion">
				<view class="picker">
					<text v-if="region.length == 0" class="blue">请选择省市区地址</text>
					<text v-else>{{ region[0] }}，{{ region[1] }}，{{ region[2] }}</text>
				</view>
			</picker>
			<text class="form-title mt20">*详细地址</text>
			<view class="form-item">
				<input type="text" placeholder="请输入详细地址" v-model="formData.address" />
			</view>
			<text class="form-title mt20">*请选择地图标点</text>
			<view class="form-item" @click="showMapDialog = true">
				<text class="blue">{{ formData.lat && formData.lng ? '已选择位置' : '请选择地图标点' }}</text>
			</view>
			<view class="form-item" v-if="formData.lat||formData.lng">
				<input type="text" style="font-size: 14px;" placeholder="请输入纬度" v-model="formData.lat" />
				<input type="text" style="font-size: 14px;" placeholder="请输入经度" v-model="formData.lng" />
				<input type="text" style="display: none;" v-model="markers[0]['title']" />
				<input type="text" style="font-size: 14px;" v-model="markers[0]['address']" />
			</view>
			<view class="popup-mask" v-if="showMapDialog" @click="closeMap">
				<view class="popup-content" @click.stop>
					<view class="map-dialog">
						<view class="dialog-header">
							<text class="title">选择位置</text>
							<text class="close" @click="closeMap">×</text>
						</view>
						<map class="map" :latitude="mapCenter.latitude" :longitude="mapCenter.longitude"
							:markers="markers" @regionchange="onMapChange">
						</map>
						<view class="dialog-footer">
							<button class="btn cancel-btn" @click="closeMap">取消</button>
							<button class="btn confirm-btn" @click="confirmLocation">确认位置</button>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="form-box">
			<text class="form-title">*电站详情照片</text>

			<view class="img-list">
				<view class="img-add" @click="uploadImage('images')" v-if="formData.images.split(',').length < 4">
					<text>+</text>
				</view>
				<view class="img-item" style="position: relative;"
					v-for="(item, index) in formData.images.split(',').filter(i => i != '')" :key="item">
					<div class="w-30 h-30 bg-red rounded-full" style="position: absolute;top: 0;right: 0;z-index: 9;">
						<image @click="formData.images = formData.images.split(',').filter(i => i != item).join(',')"
							src="/static/icon/close.png" class="w-30 h-30" mode="widthFix"></image>
					</div>
					<image :src="item" mode="widthFix"></image>

				</view>
			</view>
			<text class="num-box">{{ formData.images ? formData.images.split(',').length : 0 }}/4</text>
		</view>
		<view class="form-box">
			<text class="form-title">*电站服务电话</text>
			<view class="form-item">
				<input type="text" placeholder="请输入电站服务电话" v-model="formData.phone" />
			</view>
		</view>
		<view class="form-box">
			<text class="form-title">*营业执照照片</text>
			<view class="img-list">
				<view class="img-add" @click="uploadImage('license_image')" v-if="!formData.license_image">
					<text>+</text>
				</view>
				<view class="img-item" style="position: relative;" v-if="formData.license_image">
					<image :src="formData.license_image" mode="widthFix"></image>
					<div class="w-30 h-30 bg-red rounded-full" style="position: absolute;top: 0;right: 0;z-index: 9;">
						<image @click="formData.license_image = ''" src="/static/icon/close.png" class="w-30 h-30"
							mode="widthFix"></image>
					</div>
				</view>
			</view>
			<text class="num-box">{{ formData.license_image ? '1/1' : '0/1' }}</text>
		</view>

		<button class="submit" @click="submitForm">确认提交</button>
	</view>
</template>

<script>
export default {
	data() {
		return {
			showMapDialog: false,
			typearr:[
				'物业','个人','联营电站','非联营电站'
			],
			typeindex:0,
			formData: {
				pic: '', // 电站头像
				name: '', // 电站名称
				province: '', // 省
				province_id: '', // 省id
				city: '', // 市
				city_id: '', // 市id
				area: '', // 区
				area_id: '', // 区id
				address: '', // 详细地址
				lat: '', // 纬度
				lng: '', // 经度
				images: '', // 电站详情照片,逗号分隔
				phone: '', // 电站电话
				license_image: '', // 营业执照
				type: 1, // 类型
				status: 1, // 状态
				is_charge: 0, // 是否收费
				is_open: 1, // 是否开放
				is_park: 1, // 是否有车位
				is_power: 1, // 是否有充电桩
				power_rate: '', // 功率组
				price: '', // 单价
				speed: '' // 速度
			},
			region: [],
			mapCenter: {
				latitude: 39.910283,
				longitude: 116.396398
			},
			markers: [
				{
					id: 1,
					latitude: 39.910283,
					longitude: 116.396398,
					title:'',
					address:'',
					width:30,
					height:30,
					iconPath: '/static/icon/position.png', // 自定义图标路径，如果需要的话
				}
			]
		}
	},
	onLoad() {
		this.getInfo()
		var that = this
		uni.getLocation({
			type: 'wgs84',
			success: (res) => {
				that.markers[0].latitude = res.latitude
				that.markers[0].longitude = res.longitude
				that.mapCenter.latitude = res.latitude
				that.mapCenter.longitude= res.longitude
				if(that.formData.name==''){
					that.formData.lat = res.latitude
					that.formData.lng = res.longitude
				}
			},
			fail: (e) => {
				console.log(e)
			}
		})
	},
	methods: {
		onChangeType(e){
			this.typeindex = e.detail.value
			this.formData.type = Number(this.typeindex)+1
		},
		async getInfo() {
			const res = await this.http("get", "/api/master/my_station")
			var that = this
			if(res.data){
				this.formData = res.data
				this.typeindex = Number(this.formData.type)-1
				if (this.formData.province && this.formData.city && this.formData.area) {
					this.region = [this.formData.province, this.formData.city, this.formData.area]
				}
			}
		},

		// 省市区选择回调
		onChangeRegion(e) {
			this.region = e.target.value;
			[this.formData.province, this.formData.city, this.formData.area] = e.target.value;
		},

		// 表单验证
		validateForm() {
			if (!this.formData.pic) {
				uni.showToast({
					title: '请上传电站头像',
					icon: 'none'
				});
				return false;
			}
			if (!this.formData.name) {
				uni.showToast({
					title: '请输入电站名称',
					icon: 'none'
				});
				return false;
			}
			if (this.region.length === 0) {
				uni.showToast({
					title: '请选择省市区',
					icon: 'none'
				});
				return false;
			}
			if (!this.formData.address) {
				uni.showToast({
					title: '请输入详细地址',
					icon: 'none'
				});
				return false;
			}
			if (!this.formData.lat || !this.formData.lng) {
				uni.showToast({
					title: '请选择地图标点',
					icon: 'none'
				});
				return false;
			}
			if (!this.formData.images) {
				uni.showToast({
					title: '请上传电站详情照片',
					icon: 'none'
				});
				return false;
			}
			if (!this.formData.phone) {
				uni.showToast({
					title: '请输入电站电话',
					icon: 'none'
				});
				return false;
			}
			if (!this.formData.license_image) {
				uni.showToast({
					title: '请上传营业执照',
					icon: 'none'
				});
				return false;
			}
			// 验证手机号格式
			const phoneReg = /^1[3-9]\d{9}$/;
			if (!phoneReg.test(this.formData.phone)) {
				uni.showToast({
					title: '请输入正确的手机号',
					icon: 'none'
				});
				return false;
			}
			return true;
		},

		// 提交表单
		async submitForm() {
			if (!this.validateForm()) {
				return;
			}

			uni.showLoading({
				title: '提交中...'
			});

			try {
				const path = this.formData.id ? "/api/station/update" : "/api/station/add"
				const response = await this.http("post", path, this.formData, true)

				this.toast(response.message)
				setTimeout(function(){
					uni.redirectTo({
						url:'/pages/my/backend'
					})
				},3000)
				
				
			} catch (error) {
				console.error('提交失败:', error);
				uni.showToast({
					title: '提交失败，请重试',
					icon: 'none'
				});
			} finally {
				uni.hideLoading();
			}
		},

		// 上传图片方法
		uploadImage(type) {
			uni.chooseImage({
				count: type === 'images' ? 4 : 1,
				sizeType: ['compressed'],
				sourceType: ['album', 'camera'],
				success: async (res) => {
					const tempFilePaths = res.tempFilePaths;

					uni.showLoading({
						title: '上传中...'
					});

					try {
						const uploadTasks = tempFilePaths.map(path => {
							return new Promise((resolve, reject) => {
								uni.uploadFile({
									url: 'https://app.yinuoxinnengyuan.cn/index.php/api/index/uploads',
									filePath: path,
									name: 'file',
									success: (uploadRes) => {
										const data = JSON.parse(uploadRes.data);
										resolve(data.data.pic_path);
									},
									fail: reject
								});
							});
						});

						const uploadedUrls = await Promise.all(uploadTasks);
						console.log(uploadedUrls);

						switch (type) {
							case 'pic':
								this.formData.pic = uploadedUrls[0];
								break;
							case 'images':
								const currentImages = this.formData.images ? this.formData.images.split(',') : [];
								const newImages = [...currentImages, ...uploadedUrls];
								this.formData.images = newImages.slice(0, 4).join(',');
								break;
							case 'license_image':
								this.formData.license_image = uploadedUrls[0];
								break;
						}

						uni.showToast({
							title: '上传成功',
							icon: 'success'
						});
					} catch (error) {
						uni.showToast({
							title: '上传失败',
							icon: 'error'
						});
						console.error('上传失败:', error);
					} finally {
						uni.hideLoading();
					}
				}
			});
		},

		// 地图区域变化时的处理逻辑
		onMapChange(e) {
			console.log(e)
			
			if (e.type === 'end') {
				this.formData.lat = e.detail.centerLocation.latitude
				this.formData.lng = e.detail.centerLocation.longitude
				this.markers[0].latitude = this.formData.lat
				this.markers[0].longitude = this.formData.lng
				this.mapCenter.latitude = this.formData.lat
				this.mapCenter.longitude = this.formData.lng
				
				this.getAddress(e.detail.centerLocation.latitude, e.detail.centerLocation.longitude);

				

			}
		},
		
		getAddress(latitude, longitude) {
		  // 使用腾讯地图API获取地址名称（示例使用腾讯地图API，你也可以使用高德地图API或其他）
		  const key = 'GKHBZ-RTM3U-Q7WVG-4R3DT-HVAEH-MWFHD'; // 替换为你的API密钥
		  const url = `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${key}`;
		  var that = this
		  uni.request({
			url: url,
			method: 'GET',
			success: (res) => {
				console.log(res)
			  if ((res.data.status === 0)&&(res.data.message==='Success')) {
				const address = res.data.result.address; // 获取地址信息
				this.markers[0].title = address
				this.markers[0].address = res.data.result.formatted_addresses.recommend
				console.log('地址:', address);
				// 这里可以更新界面或进行其他操作
			  } else {
				console.error('获取地址失败:', res.data.message);
			  }
			},
			fail: (error) => {
			  console.error('请求失败:', error);
			}
		  });
		},

		closeMap() {
			this.showMapDialog = false;
		},

		confirmLocation() {
			//console.log(this.mapCenter);
			//this.formData.lat = this.mapCenter.latitude.toString();
			//this.formData.lng = this.mapCenter.longitude.toString();
			this.closeMap();
		}
	}
}
</script>

<style lang="less">
.my-content {
	width: 100%;
	padding: 30upx;
	box-sizing: border-box;

	.form-box {
		width: 100%;
		border-radius: 16upx;
		box-shadow: 0px 8px 20px 0px rgba(0, 0, 0, 0.3);
		margin-bottom: 20upx;
		padding: 30upx;
		box-sizing: border-box;

		.mt20 {
			margin-top: 40upx;
		}

		.form-title {
			font-size: 36upx;
			color: #000;
			font-weight: 700;
			display: block;
		}

		.ava-img {
			width: 200upx;
			height: 200upx;
			border-radius: 16upx;
			background: #D8D8D8;
			margin: 0 auto;
			overflow: hidden;
			display: flex;
			align-items: center;
			justify-content: center;
			position: relative;

			text {
				font-size: 100upx;
				color: #A6A6A6;
				line-height: 100upx;
				display: block;
			}

			image {
				width: 100%;
				height: auto;
				display: block;
				position: absolute;
				top: 0;
				left: 0;
			}
		}

		.form-item {
			margin: 20upx 0;
			font-size: 32upx;

			.blue {
				color: #3662EC;
			}
		}

		.img-list {
			width: 100%;
			display: flex;
			align-items: center;
			margin: 20upx 0 5upx 0;

			.img-add {
				width: 120upx;
				height: 120upx;
				border-radius: 8upx;
				background: #F1F1F1;

				text {
					font-size: 60upx;
					color: #A6A6A6;
					line-height: 120upx;
					text-align: center;
					display: block;
				}
			}

			.img-item {
				width: 120upx;
				height: 120upx;
				border-radius: 8upx;
				overflow: hidden;
				margin-left: 15upx;

				image {
					width: 100%;
					height: auto;
					display: block;
				}
			}
		}

		.num-box {
			display: block;
			width: 100%;
			text-align: right;
			font-size: 32upx;
			color: #A6A6A6;
		}
	}

	.submit {
		width: 100%;
		height: 80upx;
		border-radius: 16upx;
		background: #FF8F1F;
		box-shadow: 0px 8px 20px 0px rgba(0, 0, 0, 0.3);
		color: #fff;
		line-height: 80upx;
		font-size: 44upx;
		font-weight: 700;
		margin-top: 40upx;
	}

	.popup-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.6);
		z-index: 999;
		display: flex;
		align-items: center;
		justify-content: center;

		.popup-content {
			width: 90%;
			background: #fff;
			border-radius: 16upx;
			overflow: hidden;

			.map-dialog {
				width: 100%;

				.dialog-header {
					height: 88upx;
					display: flex;
					align-items: center;
					justify-content: space-between;
					padding: 0 30upx;
					border-bottom: 1px solid #eee;

					.title {
						font-size: 32upx;
						font-weight: 500;
						color: #333;
					}

					.close {
						font-size: 48upx;
						color: #999;
						padding: 0 20upx;
					}
				}

				.map {
					width: 100%;
					height: 600upx;
				}

				.dialog-footer {
					padding: 20upx 30upx;
					display: flex;
					justify-content: space-between;
					gap: 20upx;

					.btn {
						flex: 1;
						height: 80upx;
						border-radius: 8upx;
						font-size: 32upx;
						font-weight: 500;
						line-height: 80upx;
					}

					.cancel-btn {
						background: #F5F5F5;
						color: #666;
					}

					.confirm-btn {
						background: #3662EC;
						color: #fff;
					}
				}
			}
		}
	}
}
</style>